<template>
    <div>
        <van-checkbox-group v-model="result" ref="checkboxGroup">
            <div class='good' v-for="item in goodList" :key="item.goods_id">
                <van-checkbox :name="item.goods_id"></van-checkbox>
                <van-card
                    :price="item.goods_price"
                    :title="item.goods_name"
                    :thumb="item.goods_img"
                    >
                    <template #num >
                        <van-stepper :value="item.goods_count" @plus="add(item)" @minus="reduce(item)"/>
                    </template>
                </van-card>
            </div>
        </van-checkbox-group>
        
    </div>
</template>

<script>

import Vue from 'vue';
import { Card,Checkbox,CheckboxGroup,Stepper  } from 'vant';

Vue.use(Card);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Stepper);

export default {
    data() {
        return {
            result: [],
            goodList:[1],
            show:false
        };
    },
    created(){
        this.$http.get('/api/data/mock.json').then((ret)=>{
            this.goodList = ret.cartInfo
        })
    },
    computed: {
        total() {
            let sum = 0;
            // 循环数组，判断是否在buy中，如果在则累加小计
            this.goodList.forEach((el) => {
                if (this.result.includes(el.goods_id)) {
                    sum += el.goods_price * el.goods_count;
                }
            });
            // 保留2位小数
            return this.$store.commit("common/setTotal", sum.toFixed(2));
        },
        isCheAll() {
            return this.$store.state.common.isCheAll;
        }
    },
    methods:{
        add(item){
            item.goods_count++
            this.total
        },
        reduce(item){
            item.goods_count--
            this.total
        }
    },
    watch:{
        result(){
            this.total
            if(this.result.length == this.goodList.length){
                this.$store.commit("common/setIsCheAll", true);
            }else{
                this.$store.commit("common/setIsCheAll", false);
            }
        },
        isCheAll(bool){
            this.result = [];
            if (bool) {
                // 全选
                this.goodList.forEach((el) => {
                    this.result.push(el.goods_id);
                });
            }
        }
    }
}
</script>

<style scoped lang="scss">
.good{
    display: flex;
}
.van-checkbox{
    background-color: #fafafa;
    padding-left: 15px;
    width: 30px;
    height: 104px;
    margin-bottom: 20px;
    margin-top: 8px;
}
.van-card{
    width:100%;
    margin-bottom: 20px;
}
</style>